import Vue from "vue";
import VueRouter from "vue-router";
import user from "../views/user";
import home from "../views/home"

// 导入store实列
import store from "@/store"

Vue.use(VueRouter);

const routes = [
  // auth: 是否需要登录验证
  {
    path: "/",
    name: 'Home',
    meta: {
      index: 1,
      // auth: false
    },
    component: home,
  },
  {
    path: "/user",
    name: "User",
    meta: {
      index: 1,
      auth: true
    },
    component: user
  },
  {
    path: "/shopcart",
    name: "Shopcart",
    meta: {
      index: 1,
      auth: true
    },
    component: () => import("../views/shopcart")
  },
  {
    path: "/category",
    name: "Category",
    meta: {
      index: 1,
      auth: false
    },
    component: () => import("../views/category")
  },
  {
    // 因为这个页面是单独的，所以路由也要单独
    path: "/product-list/:id",
    name: "Product-list",
    meta: {
      index: 2,
      auth: false
    },
    component: () => import("../views/product-list/product-list.vue")
  },
  {
    path: "/login",
    name: "Login",
    meta: {
      index: 3,
      auth: false
    },
    component: () => import("../views/login")
  },
  {
    path: '/detail/:id',
    name: 'Detail',
    component: () => import ("@/views/productDetail/productDetail.vue"),
    meta: {
      index: 3
    }
  }

];

const router = new VueRouter({
  mode: "hash",
  base: process.env.BASE_URL,
  routes,
});
// 全局前置守卫，这个守卫优先级最高， 按照创建顺序调用
router.beforeEach((to, from, next) => {
  // to：到哪个路由， from，来自哪个路由，next：接下来去哪个路由（一定要执行）
  // console.log(to,from, next);
  if (to.name == 'Login' && store.getters.getIsLogin) {
    // 当要进入登录页面是判断是否登录
    next('/user')
  }
  if (to.meta.auth) { //需要验证登录的页面
    // 判断用户是否登录
    // console.log(store.getters.getIsLogin);
    if (store.getters.getIsLogin) {
      // 如果登录，就正常跳转路由
      // console.log('-----');
      next()
    }else {
      // 页面跳转异常， 点击登录后还继续执行到了这里，说明设置sessionstorage是耗时操作
      // console.log('+++');
      // 如果没有登录，就跳转至登录页面
      next('/login')
    }
  }else {
    next()
  }

})

export default router;
